package cc.rengu.redp.bizimpl.csmc.service.impl;

import cc.rengu.redp.bizimpl.csmc.dao.ReconPathInfoMapper;
import cc.rengu.redp.bizimpl.csmc.dao.ReconSceneStatMapper;
import cc.rengu.redp.bizimpl.csmc.domain.ReconPathInfo;
import cc.rengu.redp.bizimpl.csmc.domain.ReconSceneStat;
import cc.rengu.redp.bizimpl.csmc.service.IReconPathInfoService;
import cc.rengu.redp.bizimpl.csmc.vo.ReconPathInfoVO;
import cc.rengu.redp.bizimpl.enums.BizDataAuditStatusEnum;
import cc.rengu.redp.bizimpl.enums.BizDataStatusEnum;
import cc.rengu.redp.bizimpl.enums.BizOprEnum;
import cc.rengu.redp.bizimpl.enums.PageOptFlagEnum;
import cc.rengu.redp.bizimpl.upmp.common.BusinessContainer;
import cc.rengu.redp.bizimpl.upmp.domain.BizTmp;
import cc.rengu.redp.bizimpl.upmp.domain.UpmpPrivilegeCheck;
import cc.rengu.redp.bizimpl.upmp.service.IBizHisService;
import cc.rengu.redp.bizimpl.upmp.service.IBizTmpService;
import cc.rengu.redp.bizimpl.upmp.service.IUpmpPrivilegeCheckService;
import cc.rengu.redp.bizimpl.upmp.service.IUpmpSysParamService;
import cc.rengu.redp.bizimpl.upmp.vo.UpmpUserInfoVO;
import cc.rengu.redp.bizimpl.utils.Common;
import cc.rengu.redp.bizimpl.utils.CommonUtils;
import cc.rengu.redp.bizimpl.utils.DateUtils;
import cc.rengu.redp.common.domain.QueryRequest;
import cc.rengu.redp.common.exception.RedpException;
import cc.rengu.redp.common.utils.SortUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.io.Console;
import java.util.Date;

/**
 * @author guohaocong
 */
@Service
@DS("csmc")
public class ReconPathInfoServiceImpl extends ServiceImpl<ReconPathInfoMapper, ReconPathInfo> implements IReconPathInfoService {

    @Autowired
    private IUpmpSysParamService upmpSysParamService;
    @Autowired
    private IUpmpPrivilegeCheckService authPrivilegeCheckService;
    @Autowired
    private IBizTmpService bizTmpService;
    @Autowired
    private IBizHisService bizHisService;
    @Autowired
    private ReconSceneStatMapper reconSceneStatMapper;
    @Autowired
    private ReconPathInfoMapper reconPathInfoMapper;


    //    @Autowired
//    private ReconSceneStatService reconSceneStatService;
    private long oprMenuId = 1;
    private String oprMenuName = "统一对账管理:对账链路配置管理";
    private long chkMenuId = 2;
    private String chkMenuName = "统一对账管理:对账链路配置管理";
    private String webNextUrl = "/admin/csmc/reconPathInfo/edit";

    @Override
    public ReconPathInfo ByTxnChainCode(String txnChainCode, String instId) {
        LambdaQueryWrapper<ReconPathInfo> queryWrapper=new LambdaQueryWrapper();
        queryWrapper.eq(ReconPathInfo::getTxnChainCode,txnChainCode);
        queryWrapper.eq(ReconPathInfo::getInstId,instId);
        ReconPathInfo reconPathInfo = this.getOne(queryWrapper);
        return reconPathInfo;
    }

    @Override
    public IPage<ReconPathInfo> findByPage(QueryRequest request, ReconPathInfoVO reconPathInfoVO) {

        try {
            LambdaQueryWrapper<ReconPathInfo> queryWrapper = new LambdaQueryWrapper<>();
            if (!StringUtils.isEmpty(reconPathInfoVO.getInstId())) {
                queryWrapper.eq(ReconPathInfo::getInstId, reconPathInfoVO.getInstId());
            }
            if (!StringUtils.isEmpty(reconPathInfoVO.getTxnChainCode())) {
                queryWrapper.like(ReconPathInfo::getTxnChainCode, reconPathInfoVO.getTxnChainCode());
            }
            if (!StringUtils.isEmpty(reconPathInfoVO.getTxnChainDesc())) {
                queryWrapper.like(ReconPathInfo::getTxnChainDesc, reconPathInfoVO.getTxnChainDesc());
            }
            if (!StringUtils.isEmpty(reconPathInfoVO.getAuditStatus())) {
                queryWrapper.like(ReconPathInfo::getAuditStatus, reconPathInfoVO.getAuditStatus());
            }
            Page<ReconPathInfo> page = new Page<>();
            SortUtil.handlePageSort(request, page, true);
            return this.page(page, queryWrapper);
        } catch (Exception e) {
            log.error("获取信息失败", e);
            return null;
        }
    }

    @Override
    public void createReconPath(ReconPathInfoVO reconPathInfoVO) throws RedpException {
        saveData(reconPathInfoVO);
    }


    @Override
    public void updateReconPath(ReconPathInfoVO reconPathInfoVO) throws RedpException {
        saveData(reconPathInfoVO);
    }

    @Override
    public IPage<ReconSceneStat> getReconSceneIdList(ReconSceneStat reconSceneStat, QueryRequest request) throws RedpException {
        if (null == reconSceneStat) {
            return null;
        }
        try {
            LambdaQueryWrapper<ReconSceneStat> queryWrapper = new LambdaQueryWrapper<>();
            if (!StringUtils.isEmpty(reconSceneStat.getInstId())) {
                queryWrapper.eq(ReconSceneStat::getInstId, reconSceneStat.getInstId());
            }
            if (!StringUtils.isEmpty(reconSceneStat.getReconSceneId())) {
                queryWrapper.like(ReconSceneStat::getReconSceneId, reconSceneStat.getReconSceneId());
            }
            Page<ReconSceneStat> page = new Page<>();
            SortUtil.handlePageSort(request, page, true);
            return reconSceneStatMapper.selectPage(page, queryWrapper);
        } catch (Exception e) {
            log.error("获取信息失败", e);
            return null;
        }
    }


    @DS("upmp")
    private void saveData(ReconPathInfoVO reconPathInfoVO) throws RedpException {
        String flag = reconPathInfoVO.getFlag();
        String id = reconPathInfoVO.getId();
        String txnChainCode = reconPathInfoVO.getTxnChainCode();
        String lastUpddt = DateUtils.formatDate(new Date(), "yyyy-MM-dd HH:mm:ss.SSS");
        ReconPathInfo entity = new ReconPathInfo();
        //获取当前登录人信息
        UpmpUserInfoVO user = CommonUtils.getCurrentUser(upmpSysParamService);
        //前端交互的VO数据给到实体类entity
        BeanUtils.copyProperties(reconPathInfoVO, entity);
        if (PageOptFlagEnum.OPT_FLAG_ADD.getType().equals(flag)) {   ///新增
            //设置必填字段
            entity.setOprId(user.getId());
            entity.setCreateTime(lastUpddt);
            //校验权限，是否需要审核
            UpmpPrivilegeCheck privilegeCheck = authPrivilegeCheckService.getPrivilegeCheckByPrivilegeCode(user.getInstId(), "reconPathInfo:add");
            //判断权限,审核reconPathInfo.setId(null);
            if (null != privilegeCheck && BusinessContainer.YES.equals(privilegeCheck.getChecked())) {
                //设置"非正式/草稿"状态
                entity.setStatus(BizDataStatusEnum.STATUS_DRAFT.getType());
                //设置‘新增-审核’状态
                entity.setAuditStatus(BizDataAuditStatusEnum.AUDIT_STATUS_ADD_CHECKING.getType());
                //保存到数据库
                this.saveOrUpdate(entity);
                //保存记录到临时表
                bizTmpService.saveBizTmp(entity, user, user.getInstId(), BizOprEnum.OPR_ADD.getType(), lastUpddt
                        , String.valueOf(oprMenuId), oprMenuName, BizDataStatusEnum.STATUS_DRAFT.getType(), entity.getAuditStatus(),
                        entity.getId(), "", null, null, null);
            } else {
                //不要审核 设置数据状态”正式“
                entity.setStatus(BizDataStatusEnum.STATUS_NORMAL.getType());
                //设置”新增-审批通过“
                entity.setAuditStatus(BizDataAuditStatusEnum.AUDIT_STATUS_ADD_PASS.getType());
                //保存
//                this.saveOrUpdate(entity);
                baseMapper.insert(entity);
                System.out.println("======================================");
                //保存记录到历史表
                bizHisService.saveBizHisNew(entity, entity, user, user.getInstId(), BizOprEnum.OPR_ADD.getType(), lastUpddt, String.valueOf(oprMenuId), oprMenuName, entity.getId(), null, null, null);

            }
        } else if (PageOptFlagEnum.OPT_FLAG_UPDATE.getType().equals(flag)) {    //修改
            if (Common.isBlank(id)) {
                log.error("请求参数(id)异常!");
                throw new RedpException("请求参数(id)异常!");
            }
            //根据id查找数据
            ReconPathInfo dbReconPathInfo = this.getById(id);
            ReconPathInfo reconpathinfo = new ReconPathInfo();
            ReconPathInfo reconpathinfoTmp = new ReconPathInfo();
            BeanUtils.copyProperties(dbReconPathInfo, reconpathinfo);
            BeanUtils.copyProperties(dbReconPathInfo, reconpathinfoTmp);
            //设置必填字段
            entity.setOprId(user.getId());
            entity.setCreateTime(lastUpddt);
            //校验权限
            UpmpPrivilegeCheck privilegeCheck = authPrivilegeCheckService.getPrivilegeCheckByPrivilegeCode(entity.getInstId(), "reconPathInfo:update");
            if (null != privilegeCheck && BusinessContainer.YES.equals(privilegeCheck.getChecked())) {
                //设置’要修改的传入的数据‘的复核人代号
                reconpathinfo.setAuditOprId(user.getOprId());
                //设置’要修改的传入的数据‘的创建时间
                reconpathinfo.setUpdateTime(lastUpddt);
                //设置”修改-审批流程中“
                reconpathinfo.setAuditStatus(BizDataAuditStatusEnum.AUDIT_STATUS_UPD_CHECKING.getType());
                //保存修改
                this.saveOrUpdate(reconpathinfo);
                entity.setAuditStatus(BizDataAuditStatusEnum.AUDIT_STATUS_UPD_CHECKING.getType());
                //
                BeanUtils.copyProperties(entity, reconpathinfoTmp);
                bizTmpService.saveBizTmp(reconpathinfoTmp, user, user.getInstId(), BizOprEnum.OPR_UPDATE.getType(), lastUpddt
                        , String.valueOf(oprMenuId), oprMenuName, BizDataStatusEnum.STATUS_DRAFT.getType(), dbReconPathInfo.getAuditStatus(),
                        dbReconPathInfo.getId(), "", null, null, null);
            } else {
                entity.setAuditStatus(BizDataAuditStatusEnum.AUDIT_STATUS_UPD_PASS.getType());
                BeanUtils.copyProperties(entity, reconpathinfo);
                this.saveOrUpdate(reconpathinfo);

                //历史表新增
                bizHisService.saveBizHisNew(dbReconPathInfo, dbReconPathInfo, user, user.getInstId(), BizOprEnum.OPR_UPDATE.getType(), lastUpddt
                        , String.valueOf(oprMenuId), oprMenuName, reconpathinfo.getId(), null, null, null);
            }

        } else if (PageOptFlagEnum.OPT_FLAG_CHECK.getType().equals(flag)) {   //审核
            if (Common.isBlank(id)) {
                log.error("请求参数(id)异常!");
                throw new RedpException("请求参数(id)异常!");
            }
            //获取临时表数据并转换成实体对象
            BizTmp tmp = bizTmpService.getBizTmpDetail(id);
            if (Common.isBlank(tmp)) {
                String message = "根据id没有找到指定临时表数据！";
                log.error(message);
                throw new RedpException(message);
            }
            String bizdata = "";
            if (null != tmp.getBizData1()) {
                bizdata += tmp.getBizData1();
            }
            if (null != tmp.getBizData2()) {
                bizdata += tmp.getBizData2();
            }
            if (null != tmp.getBizData3()) {
                bizdata += tmp.getBizData3();
            }
            // 临时表数据
            ReconPathInfo reconpathinfoNew = JSON.parseObject(bizdata, ReconPathInfo.class);
            // 正式表数据
            QueryWrapper<ReconPathInfo> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("TXN_CHAIN_CODE", txnChainCode);
            ReconPathInfo reconpathinfo = this.getOne(queryWrapper);
            // 备份正式表数据
            ReconPathInfo reconpathinfod = new ReconPathInfo();
            BeanUtils.copyProperties(reconpathinfo, reconpathinfod);

            if (Common.isBlank(reconpathinfo) && !BizOprEnum.OPR_ADD.equals(tmp.getBizOpr())) {
                String message = "根据id没有找到指定数据！";
                log.error(message);
                throw new RedpException(message);
            }

            String opt = reconPathInfoVO.getOpt();
            if (Common.isBlank(opt)) {
                String message = "请求参数(opt)异常!";
                log.error(message);
                throw new RedpException(message);
            }

            if (PageOptFlagEnum.OPT_FLAG_PASS.getType().equals(opt)) {
                // 审批通过将临时表数据更新到正式表
                BeanUtils.copyProperties(reconpathinfoNew, reconpathinfo);
            } else {
                reconpathinfo.setAuditRefuseReason(entity.getAuditRefuseReason());
            }
            String bizOpr = "";
            if (BizDataAuditStatusEnum.AUDIT_STATUS_ADD_CHECKING.getType().equals(reconpathinfo.getAuditStatus())) {  //新增-审批流程中
                if (PageOptFlagEnum.OPT_FLAG_PASS.getType().equals(opt)) {
                    reconpathinfo.setAuditStatus(BizDataAuditStatusEnum.AUDIT_STATUS_ADD_PASS.getType());
                    reconpathinfo.setStatus(BizDataStatusEnum.STATUS_NORMAL.getType());
                } else {
                    reconpathinfo.setAuditStatus(BizDataAuditStatusEnum.AUDIT_STATUS_ADD_REJECT.getType());
                }
                bizOpr = BizOprEnum.OPR_ADD.getType();
            } else if (BizDataAuditStatusEnum.AUDIT_STATUS_UPD_CHECKING.getType().equals(reconpathinfo.getAuditStatus())) {  //修改-审批流程中
                if (PageOptFlagEnum.OPT_FLAG_PASS.getType().equals(opt)) {
                    reconpathinfo.setAuditStatus(BizDataAuditStatusEnum.AUDIT_STATUS_UPD_PASS.getType());
                    reconpathinfo.setStatus(BizDataStatusEnum.STATUS_NORMAL.getType());
                } else {
                    reconpathinfo.setAuditStatus(BizDataAuditStatusEnum.AUDIT_STATUS_UPD_REJECT.getType());
                }
                bizOpr = BizOprEnum.OPR_UPDATE.getType();
            } else if (BizDataAuditStatusEnum.AUDIT_STATUS_STOP_CHECKING.getType().equals(reconpathinfo.getAuditStatus())) { //停用-审批流程中
                if (PageOptFlagEnum.OPT_FLAG_PASS.getType().equals(opt)) {
                    reconpathinfo.setAuditStatus(BizDataAuditStatusEnum.AUDIT_STATUS_STOP_PASS.getType());
                    reconpathinfo.setStatus(BizDataStatusEnum.STATUS_STOPED.getType());
                } else {
                    reconpathinfo.setAuditStatus(BizDataAuditStatusEnum.AUDIT_STATUS_STOP_REJECT.getType());
                }
                bizOpr = BizOprEnum.OPR_UPDATE.getType();
            } else if (BizDataAuditStatusEnum.AUDIT_STATUS_USE_CHECKING.getType().equals(reconpathinfo.getAuditStatus())) { //启用-审批流程中
                if (PageOptFlagEnum.OPT_FLAG_PASS.getType().equals(opt)) {
                    reconpathinfo.setAuditStatus(BizDataAuditStatusEnum.AUDIT_STATUS_USE_PASS.getType());
                    reconpathinfo.setStatus(BizDataStatusEnum.STATUS_NORMAL.getType());
                } else {
                    reconpathinfo.setAuditStatus(BizDataAuditStatusEnum.AUDIT_STATUS_USE_REJECT.getType());
                }
                bizOpr = BizOprEnum.OPR_UPDATE.getType();
            } else if (BizDataAuditStatusEnum.AUDIT_STATUS_CANCEL_CHECKING.getType().equals(reconpathinfo.getAuditStatus())) { //注销-审批流程中
                if (PageOptFlagEnum.OPT_FLAG_PASS.getType().equals(opt)) {
                    reconpathinfo.setAuditStatus(BizDataAuditStatusEnum.AUDIT_STATUS_CANCEL_PASS.getType());
                    reconpathinfo.setStatus(BizDataStatusEnum.STATUS_CANCELED.getType());
                } else {
                    reconpathinfo.setAuditStatus(BizDataAuditStatusEnum.AUDIT_STATUS_CANCEL_REJECT.getType());
                }
                bizOpr = BizOprEnum.OPR_UPDATE.getType();
            }
            // 状态赋值完成后，入库正式表
            this.saveOrUpdate(reconpathinfo);
            //
            if (PageOptFlagEnum.OPT_FLAG_PASS.getType().equals(opt)) {
                //审批通过将正式表更新到历史表
                bizHisService.saveBizHisNew(reconpathinfo, reconpathinfod, user, user.getInstId(), bizOpr, lastUpddt, String.valueOf(oprMenuId), oprMenuName, String.valueOf(reconpathinfo.getId()), null, null, null);
            }
            // 修改临时表的审核状态等字段
            bizTmpService.saveBizTmp(reconpathinfo, user, user.getInstId(), bizOpr, lastUpddt, String.valueOf(oprMenuId), oprMenuName, reconpathinfo.getStatus(), reconpathinfo.getAuditStatus(), String.valueOf(reconpathinfo.getId()), webNextUrl, null, null, null);


        } else if (PageOptFlagEnum.OPT_FLAG_STOP.getType().equals(flag)
                || PageOptFlagEnum.OPT_FLAG_USE.getType().equals(flag)
                || PageOptFlagEnum.OPT_FLAG_CANCEL.getType().equals(flag)) {  //停用、启用、注销
            if (Common.isBlank(id)) {
                String message = "请求参数(id)异常!";
                log.error(message);
                throw new RedpException(message);
            }
            // 正式表数据
            QueryWrapper<ReconPathInfo> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("TXN_CHAIN_CODE", txnChainCode);
            ReconPathInfo reconpathinfo = this.getOne(queryWrapper);

            if (Common.isBlank(reconpathinfo)) {
                String message = "根据id没有找到指定数据";
                log.error(message);
                throw new RedpException(message);
            }
            // 备份正式表数据
            ReconPathInfo reconpathinfod = new ReconPathInfo();
            BeanUtils.copyProperties(reconpathinfo, reconpathinfod);
            UpmpPrivilegeCheck privilegeCheck = new UpmpPrivilegeCheck();
            String bizOpr = "";
            if (PageOptFlagEnum.OPT_FLAG_STOP.getType().equals(flag)) {
                bizOpr = BizOprEnum.OPR_STOP.getType();
                //校验权限
                privilegeCheck = authPrivilegeCheckService.getPrivilegeCheckByPrivilegeCode(entity.getInstId(), "reconPathInfo:stop");
                if (null != privilegeCheck && BusinessContainer.YES.equals(privilegeCheck.getChecked())) {
                    reconpathinfo.setAuditStatus(BizDataAuditStatusEnum.AUDIT_STATUS_STOP_CHECKING.getType());
                } else {
                    reconpathinfo.setAuditStatus(BizDataAuditStatusEnum.AUDIT_STATUS_STOP_PASS.getType());
                    reconpathinfo.setStatus(BizDataStatusEnum.STATUS_STOPED.getType());
                }
            } else if (PageOptFlagEnum.OPT_FLAG_USE.getType().equals(flag)) {

                bizOpr = BizOprEnum.OPR_USE.getType();
                privilegeCheck = authPrivilegeCheckService.getPrivilegeCheckByPrivilegeCode(entity.getInstId(), "reconPathInfo:start");
                if (null != privilegeCheck && BusinessContainer.YES.equals(privilegeCheck.getChecked())) {
                    reconpathinfo.setAuditStatus(BizDataAuditStatusEnum.AUDIT_STATUS_USE_CHECKING.getType());
                } else {
                    reconpathinfo.setAuditStatus(BizDataAuditStatusEnum.AUDIT_STATUS_USE_PASS.getType());
                    reconpathinfo.setStatus(BizDataStatusEnum.STATUS_NORMAL.getType());
                }
            } else if (PageOptFlagEnum.OPT_FLAG_CANCEL.getType().equals(flag)) {

                bizOpr = BizOprEnum.OPR_CANCEL.getType();
                privilegeCheck = authPrivilegeCheckService.getPrivilegeCheckByPrivilegeCode(entity.getInstId(), "reconPathInfo:cancel");
                if (null != privilegeCheck && BusinessContainer.YES.equals(privilegeCheck.getChecked())) {
                    reconpathinfo.setAuditStatus(BizDataAuditStatusEnum.AUDIT_STATUS_CANCEL_CHECKING.getType());
                } else {
                    reconpathinfo.setAuditStatus(BizDataAuditStatusEnum.AUDIT_STATUS_CANCEL_PASS.getType());
                    reconpathinfo.setStatus(BizDataStatusEnum.STATUS_CANCELED.getType());
                }
            }
//            this.saveOrUpdate(reconpathinfo);
            System.out.println(reconpathinfo);
            LambdaUpdateWrapper<ReconPathInfo> lambdaUpdateWrapper = new LambdaUpdateWrapper();
            lambdaUpdateWrapper.eq(ReconPathInfo::getTxnChainCode, reconpathinfo.getTxnChainCode());
            lambdaUpdateWrapper.set(ReconPathInfo::getAuditStatus, reconpathinfo.getAuditStatus());
            lambdaUpdateWrapper.set(ReconPathInfo::getStatus, reconpathinfo.getStatus());
            int row = reconPathInfoMapper.update(null, lambdaUpdateWrapper);
            if(row==0){
                reconPathInfoMapper.insert(reconpathinfo);
            }

            if (null != privilegeCheck && BusinessContainer.YES.equals(privilegeCheck.getChecked())) {
                //检查临时表是否有数据，如果没用则新增
                bizTmpService.saveBizTmp(reconpathinfo, user, user.getInstId(), bizOpr, lastUpddt
                        , String.valueOf(oprMenuId), oprMenuName, reconpathinfo.getStatus(), reconpathinfo.getAuditStatus(), reconpathinfo.getId(), webNextUrl, null, null, null);
            } else {
                bizHisService.saveBizHisNew(reconpathinfo, reconpathinfod, user, user.getInstId(), bizOpr, lastUpddt
                        , String.valueOf(oprMenuId), oprMenuName, String.valueOf(reconpathinfo.getId()), null, null, null);
            }
        }


    }

}

